<template>
  <el-upload
      class="upload-demo"
      drag
      :headers="headers"
      :action="uploadAction"
      multiple
      v-loading="loading"
      :show-file-list="false"
      :before-upload="onBeforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
  >
    <el-icon class="el-icon--upload">
      <upload-filled/>
    </el-icon>
    <div class="el-upload__text">
      拖拽至此区域或 <em>点击上传</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        不限制文件类型和大小，但不建议超过500M。
      </div>
    </template>
  </el-upload>
  <el-table :data="fileList" stripe style="width: 100%; margin-top: 10px; height: 220px">
    <!--    <el-table-column fixed type="expand" prop="originalName" label="文件名称" width="180">-->
    <el-table-column fixed prop="originalName" width="80" label="文件">
      <template #default="scope">
        <el-image style="width: 50px; height: 50px"
                  :src="scope.row.link" fit="fill">
            <template #error>
              <div class="image-slot">
                <p>{{ fileType(scope.row) }}</p>
              </div>
            </template>
        </el-image>
      </template>
    </el-table-column>
    <el-table-column prop="link" label="在线地址" show-overflow-tooltip/>
    <el-table-column label="操作" width="100">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="toCopy(scope.row)">复制</el-button>
        <el-button link type="primary" size="small" @click="toDel(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script lang="ts">
import { UploadAction } from "@/api";
import {UploadProps, ElMessage} from 'element-plus'
import {ref, computed} from 'vue';
import {copy} from "@/utils/tools";
import { tr } from 'element-plus/es/locale';

export default {
  name: 'PicBed',
  setup() {
    interface Row {
      link: string
      originalName: string
    }
    const uploadAction = ref(UploadAction)
    const loading = ref(false)
    /* 请求头 */
    const headers = computed(() => {
      return {
        Authorization: localStorage.getItem('MINITOOLBOX_tk')
      }
    })
    // 附件类型
    const fileType = computed(() => {
      return <T extends Row>(row: T): string => {
      const flieArr = row.originalName.split('.'); // 根据.分割数组
      const suffix = flieArr[flieArr.length - 1]; // 取最后一个
      return suffix
      }
    })
    /* 数据源 */
    const fileList = ref<UploadProps[]>([])
    if(localStorage.getItem('MINITOOLBOX_PICBED_FILES')) {
      const listStr: string | null = localStorage.getItem('MINITOOLBOX_PICBED_FILES')
      const list: any[] | null = listStr ? JSON.parse(listStr) : null
      list && list instanceof Array && list.forEach((li: any) => {
        fileList.value.push(li)
      })
    }
    const updateStorage = () => {
      localStorage.setItem('MINITOOLBOX_PICBED_FILES', JSON.stringify(fileList.value))
    }
    const onBeforeUpload = (file: any) => {
      console.log('file ---', file)
      loading.value = true
    }
    const handleSuccess: UploadProps['onSuccess'] = (res: any) => {
      loading.value = false
      if(res.code === 401) {
        ElMessage.success(`${res.msg}, 正在自动登录...`)
        setTimeout(() => {
          window.location.reload()
        }, 1000);
        return
      }
      let msg = '上传失败'
      if (res.success) {
        msg = '上传成功！'
        fileList.value.push(res.data)
      }
      updateStorage()
      ElMessage.success(res.msg || msg)
    }
    const toCopy = <T extends Row>(row: T) => {
      copy(row.link, '链接复制成功！')
    }
    const handleError = (err: any, file: any, fileList: any) => {
        console.log('上传失败', err)
        loading.value = false
    }

    const toDel = (row: any) => {
      const index = fileList.value.findIndex((f: any) => f.link === row.link)
      fileList.value.splice(index, 1)
      updateStorage()
    }

    return {uploadAction, headers, fileType, fileList, loading, onBeforeUpload, handleSuccess, toCopy, toDel}
  }
}
</script>

<style lang="scss">
.el-upload-dragger {
  padding: 10px;

  .el-icon {
    font-size: 45px;
  }

  .el-upload__text {
    font-size: 12px;
  }
}
.el-image {
    .image-slot {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }
  }
</style>
